<template>

  <div class="dgoodsform">
    <el-form :model="donategoods" label-width="120px" :rules="dgoodsRules" ref="dgoodsRef">
      <el-form-item label="捐赠物品" prop="dtitle">
        <!--        <el-input v-model="donategoods.dtitle"/>-->
        <el-select v-model="donategoods.dtitle" class="m-2" placeholder="选择类型" >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="捐赠人姓名" prop="dname">
        <el-input v-model="donategoods.dname"/>
      </el-form-item>
      <el-form-item label="捐赠手机号" prop="dphone">
        <el-input v-model="donategoods.dphone"/>
      </el-form-item>
      <el-form-item label="预约取件时间" prop="dfetchdata">
        <div class="block">
          <el-date-picker
              v-model="donategoods.dfetchdata"
              type="datetime"
              placeholder="Select date and time"

          />
        </div>
      </el-form-item>
      <el-form-item label="选择取件位置:" prop="dposition">
        <div class="detailstate">{{ realAdd }}</div>
        <div class="drawStation">
          <div id="draw-station-container">

          </div>
        </div>
      </el-form-item>
    </el-form>

    <div class="button">
      <el-button @click="subdgoods()">提交</el-button>
      <el-button @click="reset()">重置</el-button>
    </div>
  </div>
</template>

<script>
import * as AMapLoader from "@amap/amap-jsapi-loader";
import doThis from "@/api/getData";
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name: "DonateGoods",
  data() {
    return {
      donategoods: {
        dtitle: null,
        dfetchdata: null,
        dphone: null,
        dname: null,
        dposition: null,
      },
      options: [
        {label: "衣物", value: "衣物"},
        {label: "生活用品", value: "生活用品"},
        {label: "书籍", value: "书籍"},
        {label: "电子产品", value: "电子产品"},
        {label: "运动器材", value: "运动器材"},
        {label: "其他", value: "其他"},
      ],
      dgoodsRules: {
        dtitle: [
          {required: true, message: '选择类型', trigger: 'blur'},
          {min: 2, max: 20, message: '长度必须大于2个字符，小于8个字符', trigger: 'blur'},
        ],
        dfetchdata: [
          {required: true, message: '请输选择上门时间', trigger: 'blur'},
        ],
        dphone: [
          {required: true, message: '请输入联系电话', trigger: 'blur'},
          {min: 11, max: 11, message: '电话输入有误', trigger: 'blur'},

        ],
        dname: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 2, max: 5, message: '长度必须大于2个字符，小于5个字符', trigger: 'blur'},
        ],
        dposition: [
          {required: true, message: '请选择寄件位置', trigger: 'blur'},
        ]
      },
      defcenter: {
        x: 121.380676,
        y: 37.539237,
      },
      // 地图对象
      // 地图实例对象
      map: null,
      // 标点对象
      marker: null,

      // 真实地址
      realAdd: ''
    }
  },
  mounted() {
    this.$checkLogin()
    //获得当前ip所在经纬度
    /*    doThis.doGet("https://restapi.amap.com/v3/ip", {
          output: 'json',
          key: 'f5e5504bd7700d7045245f8b7ca45b29'
        })
            .then(res => {
              console.log(res.rectangle.split(';')[0])
              this.defcenter.x = res.rectangle.split(';')[0].split(',')[0]
              this.defcenter.y = res.rectangle.split(';')[0].split(',')[1]
            })*/
    this.initMap()
  },
  methods: {
    /**
     * 创建地图
     */
    initMap() {
      AMapLoader.load({
        key: '105771500d5f91b00104a0d28ea72c41', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Scale', 'AMap.PlaceSearch', 'AMap.AutoComplete'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
          .then((AMap) => {
            this.map = new AMap.Map("draw-station-container", {
              resizeEnable: true,
              //设置地图容器id
              viewMode: "3D", //是否为3D地图模式
              zoom: 15, //初始化地图级别
              center: [this.defcenter.x, this.defcenter.y], //初始化地图中心点位置
              mapStyle: 'amap://styles/macaron', //设置地图的显示样式
            })
            // 地图点击事件
            this.map.on('click', this.clickMapHandler)
          })
    },
    // 点击地图事件
    clickMapHandler(e) {
      // 将经纬度放在data里面用于传向数据库
      this.donategoods.dposition = e.lnglat.getLng() + "," + e.lnglat.getLat()
      // 用于重置时初始化地图
      this.defcenter.x = e.lnglat.getLng()
      this.defcenter.y = e.lnglat.getLat()
      this.addFlg(e)
      //将经纬度转换为真实地址
      axios.get("https://restapi.amap.com/v3/geocode/regeo", {
        params: {
          output: 'json',
          location: e.lnglat.getLng() + ',' + e.lnglat.getLat(),
          key: 'f5e5504bd7700d7045245f8b7ca45b29',
          radius: '1000',
          extensions: 'all'
        }
      }).then(res => {
        console.log(e.lnglat.getLng() + ',' + e.lnglat.getLat())
        console.log(res.data.regeocode.formatted_address)
        this.realAdd = res.data.regeocode.formatted_address
      })

    },
    /**
     * 地图添加蓝色标点
     * @param e
     */
    addFlg(e) {
      // 清空标记
      if (this.marker != null) {
        this.map.remove(this.marker)
      }
      this.marker = null
      // 生成标记
      // eslint-disable-next-line no-undef
      this.marker = new AMap.Marker({
        map: this.map,
        position: [e.lnglat.getLng(), e.lnglat.getLat()],
      })
    }
    ,
    //提交后台
    subdgoods() {

      this.$refs['dgoodsRef'].validate((res) => {
        if (res) {

          let data = new FormData
          data.append("dtitle", this.donategoods.dtitle)
          data.append("dfetchdata", this.donategoods.dfetchdata)
          data.append("dphone", this.donategoods.dphone)
          data.append("dname", this.donategoods.dname)
          data.append("dposition", this.donategoods.dposition)
          doThis.doPost("/donategoods/add", data).then(res => {
            console.log(res)
            if (res.code == 0) {
              // alert(res.msg)
              ElMessage.error(res.msg)
              this.reset()
            } else {
              // alert(res.msg)
              ElMessage.error(res.msg)
            }
          })
        }
      })

    },
    reset() {
      this.initMap()
      this.donategoods = {
        dtitle: null,
        dfetchdata: null,
        dphone: null,
        dname: null,
        dposition: null,

      }
    }
  },
  beforeUnmount() {
    console.log()
    this.map.destroy('beforeUnmount running');
    this.map = null
    this.marker = null
  }
}
</script>

<style scoped>
.demo-datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-datetime-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-datetime-picker .block:last-child {
  border-right: none;
}

.demo-datetime-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.dgoodsform {
  margin: 0 auto;
  width: 500px;
}


.block {

}

.drawStation #draw-station-container {
  padding: 0;
  /* margin: 20px 0 20px 0; */
  margin: 50px auto;
  width: 500px;
  height: 300px;
}

.detailstate {
  font-size: 16px;
  height: 10px;
}

.el-input {
//width: 220px; margin: 10px 0 0 10px; z-index: 5;
}

.mydiv {
  margin: 110px 250px;
  line-height: 300px;
  width: 25px;
  position: relative;
  height: 40px;
  z-index: 6;
}
</style>